<?php
namespace api\modules\v1\models\address;

use common\models\Functions;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class ConfigAddress extends \common\models\address\ConfigAddress
{

    public function getSubByPid($pid = 1) {
        $pid = empty($pid) ? 1 : $pid;
        $where['parentid'] = $pid;

        $list = static::getByWhere($where, ['id', "areaname as name"]);
        foreach ($list as $k => $v) {
            $list[$k]['id'] = (int) $v['id'];
        }
        return Functions::formatRestAPI(0, '', $list);
    }

    public function getAllAddress() {
        $where['level'] = [1,2,3];
        $list = static::getCacheByWhere($where, ['id', "areaname as name","parentid as parentId"]);
        $result = null;
        $tmp = [];
        foreach ($list as $k => $v) {
            if ($v['id'] == 1) {
                continue;
            }

            if ($v['parentId'] != 1) {
                $tmp[] = [
                    'value' => $v['id'],
                    'parent' => $v['parentId'],
                    'name' => $v['name'],
                ];
            } else {
                $tmp[] = [
                    'value' => $v['id'],
                    'name' => $v['name'],
                ];
            }
        }
        $result = $tmp;
        return Functions::formatRestAPI(0, '', $result);
    }

    public static function checkAddress($p = 0, $c = 0, $a = 0) {
        $province = static::getOneInfoById($p);
        if (empty($p) || empty($province)) {
            throw new Exception('未知省份');
        }
        $city = static::getOneInfoById($c);
        if (empty($c) || empty($city) || $city['parentid'] != $p) {
            throw new Exception('未知省份');
        }
        $area = static::getOneInfoById($a);
        if (empty($a) || empty($area) || $area['parentid'] != $c) {
            throw new Exception('未知省份');
        }
    }

    public static function getAddress($p = 0, $c = 0, $a = 0) {
        $where['id'] = [$p, $c, $a];
        $map = static::getByWhere($where);
        $map = ArrayHelper::index($map,'id');
        return [
            'province' => $map[$p]['areaname'],
            'city' => $map[$c]['areaname'],
            'area' => $map[$a]['areaname'],
        ];
    }

    public static function getAddressStr($p = 0, $c = 0, $a = 0) {
        $where['id'] = [$p, $c, $a];
        $map = static::getByWhere($where);
        $map = ArrayHelper::index($map,'id');
        return $map[$p]['areaname'] . $map[$c]['areaname'] .$map[$a]['areaname'];
    }


}
